"""
    Defines functions for saving and loading image resources.
"""

import os
from xml.etree import ElementTree as ET
import pygame
from .. import debug, resource
from ..error import FormatError
from ..misc import strbool
from ..image import Image
from .util import get_elem_value
from .surface import load as load_surface

__all__ = (
    'load'
)

VERSION = '0.03'
    
def load(fileOrPath,convertSurf=False,alphaSurf=False):
    """ Loads an Image resource.
        
        Opens image files that meet the version %s image resource file
        specification. (See the docs for more info.)
        
        Can also load surface files as images with default values.
        
        TODO: Allow images to be loaded from compressed files.
        FIXME: May not properly handle file objects in some cases??
    """%VERSION
    
    # See if the image is really a surface
    try:
        surf = load_surface(fileOrPath,convertSurf,alphaSurf)
        return Image(surf=surf)
    except (IOError,pygame.error):
        pass
    
    debug.message("Loading image '%s'"%fileOrPath)
    
    # Get the leading path if available
    try:
        head,tail = os.path.split(fileOrPath)
    except (AttributeError,TypeError):
        head = ''
    
    # Start parsing
    tree = ET.parse(fileOrPath)
    root = tree.getroot()
    
    # Verify the version
    vers = root.get('version').strip()
    if vers != VERSION:
        raise FormatError("Bad version number '%s'"%vers)
    
    # Verify the root tag
    if root.tag != 'image':
        raise FormatError("Image root element tag is not 'image'.")
    
    # Get offset values
    elem = root.find('offset')
    if elem is not None:
        offset = (get_elem_value(elem.find('x'), int, 0),
                  get_elem_value(elem.find('y'), int, 0))
    else:
        offset = (0,0)
    
    # Get default position values
    elem = root.find('pos')
    if elem is not None:
        pos = (get_elem_value(elem.find('x'), int, 0),
               get_elem_value(elem.find('y'), int, 0))
    else:
        pos = (0,0)
    
    # Get surface information
    elem = root.find('surface')
    if elem is None:
        raise FormatError("Image resource file has no surface.")
    src = elem.get('src',None)
    ref = elem.get('ref',None)
    # If the 'src' attribute is present, use it
    if src is not None:
        # If fileOrPath is a path, get the directory of the path
        if isinstance(fileOrPath,str):
            head,tail = os.path.split(fileOrPath)
        surf = load_surface(os.path.join(head,src),
                            strbool(elem.get('convert',False)),
                            strbool(elem.get('alpha', False)))
    # If 'src' is not present but 'ref' is,
    elif ref is not None:
        surf = resource.depend(ref)
    # If neither attribute is present, fail.
    else:
        raise FormatError("Image resource surface element has no src and no ref.")
    
    # Create the Image object
    img = Image(pos,offset,surf)
    
    return img

def _autoload(agent):
    """ Internal function.
        Autoloader for Image resources.
    """
    return load(agent.src,
                 agent.extra['convert'] if 'convert' in agent.extra else False,
                 agent.extra['alpha'] if 'alpha' in agent.extra else False)
